package gvalidator

import (
	"go.uber.org/zap"
	"math/big"
	"net"
	"strings"
	"wzgames/internal/constant"
	"wzgames/pkg/logger"
	"wzgames/pkg/utils/stringutil"
)

const s6 = "]:"

func FindClientIP(str string) string {
	ipStr := str
	arr := strings.Split(ipStr, constant.Comma)
	l := len(arr)
	if l == 0 {
		return constant.EmptyStr
	} else if l > 1 {
		ipStr = stringutil.Trim(arr[0], "")
		logger.Warn("[IP] multi address on FindClientIP", zap.String("Input", str))
	}
	if strings.Contains(ipStr, constant.Dot) && strings.Contains(ipStr, constant.Colon) || strings.Contains(ipStr, s6) {
		host, _, err := net.SplitHostPort(ipStr)
		if err != nil {
			logger.Error("[IP] split address fail on FindClientIP", zap.String("Input", str), zap.Error(err))
			return ipStr
		}

		return host
	}

	return ipStr
}

func IpToBinary(ipStr string) []byte {
	if ipStr == constant.EmptyStr {
		return []byte{}
	}
	addr := net.ParseIP(ipStr)
	ipInt := big.NewInt(0)
	if addr != nil {
		v4 := addr.To4()
		if v4 != nil {
			ipInt.SetBytes(v4)
		} else if addr.To16() != nil {
			ipInt.SetBytes(addr.To16())
		}
	}
	return ipInt.Bytes()
}
